#ifndef _THREAD_H_
#define _THREAD_H_

#include <iostream>
#include <functional>
#include <string.h>
#include<stdlib.h>
#include<pthread.h>


namespace ThreadModule
{
    static uint32_t number = 1;
    class Thread
    {
        using func_t = std::function<void()>;//保存用户想要执行的任务
        private:
        void EnableDetach()
        {
            std::cout<<"线程已经被分离了"<<std::endl;
            _isdetach = true;
        }


        void EnableRunning()
        {
            _isrunning = true;
        }

        static void* Routine(void* args)//static成员函数没有隐含的this指针
        {
            Thread *self = static_cast<Thread*>(args);
            self->EnableRunning();
            if(self->_isdetach) self->Detach();
            pthread_setname_np(self->_tid,self->_name.c_str());
            self->_func();//回调处理？？

            return nullptr;
        }
        

    public:
        Thread(func_t func) 
            : _tid(0), _isdetach(false), _isrunning(false), res(nullptr), _func(func)
        {
            _name = "thread-" + std::to_string(number++);
        }

        bool Start()
        {
            if(_isrunning) return false;

            int n = pthread_create(&_tid,nullptr,Routine,this);//让Routine能够访问当前对象的成员变量和方法

            if(n!=0)
            {
                std::cerr<<"create thread error"<<strerror(n)<<std::endl;
                return false;
            }
            else
            {
                std::cout<<_name<<" create success"<<std::endl;
                return true;
            }

        }

        bool Stop()
        {
            if(_isrunning)
            {
                int n = pthread_cancel(_tid);
                if(n!=0)
                {
                    std::cerr<<"stop thread error"<<strerror(n)<<std::endl;
                    return false;
                }
                else
                {
                    _isrunning = false;
                    std::cout<<_name<<" stop"<<std::endl;
                    return true;
                }
            }

            return false;
        }

        void Join()
        {
            if(_isdetach) 
            {
                std::cout<<"线程已经被分离，不需要被等待"<<std::endl;
                return ;
            }

            int n = pthread_join(_tid,&res);
            if(n!=0)
            {
                std::cerr<<"Join thread error"<<strerror(n)<<std::endl;
            }
            else
            {
                std::cout<<"Jion success"<<std::endl;
            }
        }

        void Detach()
        {
            if(_isdetach) return;

            if(_isrunning) pthread_detach(_tid);
            EnableDetach();
        }

        std::string Name()
        {
            return _name;
        }
        ~Thread()
        {
        }

    private:
        pthread_t _tid;
        std::string _name;
        bool _isdetach;
        bool _isrunning;
        void *res;
        func_t _func;
    };
}

#endif